﻿using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Flurl;
using Newtonsoft.Json;
using ZilLion.Core.ConfigManager.Manager;
using ZilLion.Core.Unities.UnitiesMethods;
using ZilLion.TaskManager.Entity;
using ZilLion.TaskManager.Entity.Config;
using ZilLion.TaskManager.Entity.Entity;
using ZilLion.TaskManager.Entity.Response;

namespace ZilLion.TaskManager.Repository
{
    public class TaskConfigRespository : ITaskConfigRespository
    {
        public TaskConfigResponse GetConfigResponse()
        {
            var url = Url.Combine(TaskManagerGlobalSetting.GetInstance().ManagerServiceHost, "Api",
                "TaskPlatform",
                "TaskConfig", "GetAllTaskConfig"
            );
            return HttpHelper.HttpRequestGet<TaskConfigResponse>($"{url} ");
        }

        public void DownLoadPackage(string mouduleid, string savepath)
        {
            var url = Url.Combine(TaskManagerGlobalSetting.GetInstance().ManagerServiceHost, "Api",
                "TaskPlatform",
                "DownloadTaskPackage", mouduleid
            );
            DownloadFile($"{url} ",
                savepath);
        }

        public bool SaveConfig(TaskConfig entity)
        {
            var url = Url.Combine(TaskManagerGlobalSetting.GetInstance().ManagerServiceHost, "Api",
                "TaskPlatform",
                "TaskConfig", "SaveTaskConfig"
            );


            var httpcontent = new StringContent(JsonConvert.SerializeObject(entity))
            {
                Headers = {ContentType = new MediaTypeHeaderValue("application/json")}
            };


            var response = HttpHelper.HttpRequestPost<ResponseBase>($"{url} ", httpcontent);


            return response != null && response.IsSuccess;
        }

        public TaskConfigResponse GetTaskConfigById(string taskid)

        {
            var url = Url.Combine(TaskManagerGlobalSetting.GetInstance().ManagerServiceHost, "Api",
                "TaskPlatform",
                "TaskConfig", "GetTaskConfig"
            );
            return HttpHelper.HttpRequestGet<TaskConfigResponse>($"{url}?taskid={taskid} ");
        }

        private void DownloadFile(string url, string saveFilePath)
        {
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;
            //不验证服务端https证书

            var saveFileInfo = new FileInfo(saveFilePath);
            var file = saveFileInfo.Name;
            if (saveFileInfo.Directory == null) return;
            var dir = saveFileInfo.Directory.FullName;

            var tempsaveFilepath = Path.Combine(dir, file + ".packagetmp");


            using (var client = new HttpClient())
            {
                client.Timeout = new TimeSpan(0, 0, 0, 300);//5分钟超时

                var result = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).Result;
                //只读httpheader即可返回，不用等待获取下载文件内容
                if (File.Exists(tempsaveFilepath))
                {
                    var targetFileinfo = new FileInfo(tempsaveFilepath);
                    if (result != null && targetFileinfo.Length >= result.Content.Headers.ContentLength)
                        File.Delete(tempsaveFilepath);
                }

                var downloadresult = DownloadFileWithResume(url, tempsaveFilepath);
                if (downloadresult)
                {
                    var fileinfo = new FileInfo(tempsaveFilepath);
                    fileinfo.Rename(saveFileInfo.Name); //把tmp 后缀名文件重新改为正常文件名
                }
            }
        }


        /// <summary>
        ///     断点续传下载
        /// </summary>
        /// <param name="sourceUrl"></param>
        /// <param name="destinationPath"></param>
        private static bool DownloadFileWithResume(string sourceUrl, string destinationPath)
        {
            try
            {
                long existLen = 0;
                FileStream saveFileStream;
                if (File.Exists(destinationPath))
                {
                    var fInfo = new FileInfo(destinationPath);
                    existLen = fInfo.Length; //已下载流长度
                }
                if (existLen > 0) //如果文件存在则FileMode.Append 否则Create
                    saveFileStream = new FileStream(destinationPath,
                        FileMode.Append, FileAccess.Write,
                        FileShare.ReadWrite);
                else
                    saveFileStream = new FileStream(destinationPath,
                        FileMode.Create, FileAccess.Write,
                        FileShare.ReadWrite);


                var httpWebRequest = (HttpWebRequest)WebRequest.Create(sourceUrl);
                httpWebRequest.AddRange((int)existLen);
                var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var respStream = httpWebResponse.GetResponseStream())
                {
                    var timout = httpWebRequest.Timeout;
                    respStream?.CopyTo(saveFileStream);
                }
                saveFileStream.Close();
                saveFileStream.Dispose();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}